package com.competitions.videoedithelper.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.competitions.videoedithelper.dao.IGeneratedAudioDao;
import com.competitions.videoedithelper.entity.ResponseModel;
import com.competitions.videoedithelper.service.ITextToSpeechService;
import com.competitions.videoedithelper.utils.AudioUtil;
import com.competitions.videoedithelper.utils.UploadFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Mapler
 */
@Service
public class TextToSpeechServiceImpl implements ITextToSpeechService {
    private IGeneratedAudioDao iGeneratedAudioDao;

    @Autowired
    public TextToSpeechServiceImpl(IGeneratedAudioDao iGeneratedAudioDao) {
        this.iGeneratedAudioDao = iGeneratedAudioDao;
    }

    @Override
    public ResponseModel textToSpeech(JSONObject jsonObject) {
        String filePath = jsonObject.getString("videoPath");
        String file = filePath.replace("/root/home/userfiles/audios","/share");
        String text = jsonObject.getString("text");
        RestTemplate restTemplate = new RestTemplate();
        try {
            Map<String, String> vars = new HashMap<>(2);
            vars.put("file",file);
            vars.put("text",text);
            String path,url;
            String result = restTemplate.getForObject("http://localhost:8089/synthesis?file={file}&text={text}", String.class,vars);
            if(result != null) {
                path = result.replace("/share", "/root/home/userfiles/audios");
                url = result.replace("/share", "http://121.43.142.18:8066/userfiles/audios");
            }else {
                path = "";
                url = "";
            }
            double audioDuration;
            double audioSize;
            File audio=new File(path);
            audioSize=audio.length();
            audioDuration= AudioUtil.getAudioTime(audio);
            String startPosition = jsonObject.getString("startPosition");
            String endPosition = jsonObject.getString("endPosition");
            int videoId = jsonObject.getInteger("videoId");
            iGeneratedAudioDao.insertAudio(audioDuration,audioSize,path,url,videoId,startPosition, endPosition);
            Map<String,String> data = new HashMap<>(2);
            data.put("filePath",path);
            data.put("url",url);
            return new ResponseModel(200,"成功",data);
        } catch (RestClientException e) {
            e.printStackTrace();
            return new ResponseModel(199,"失败");
        }
    }
    }
